import React, { CSSProperties, useState } from 'react'
import { DATASOURCE_INPUT_ID } from './common'
const mapFun = (template: any) => (template.unit == 'auto' ? 'auto' : `${template.value}${template.unit}`)
function EditRender({ data, slots }: any) {
  const template = data.templates?.map?.(mapFun)?.join?.(' ')
  const [columnGap,rowGap] = data.gap
  const style: CSSProperties = {
    columnGap,
    rowGap,
    display: 'grid',
    gridAutoFlow: data.direction == 'ver' ? 'column' : 'row'
  }
  if (data.direction == 'hor') {
    style.gridTemplateColumns = template
  } else {
    style.gridTemplateRows = template
  }

  const items: React.ReactElement[] = []
  for (let c = 1; c <= data.templates?.length || 0; c++) {
    const id = `slot_${1}x${c}`
    items.push(<div>{slots[id]?.render?.()}</div>)
  }
  return <div style={style}>{items}</div>
}


function RuntimeRender({ data, slots, inputs }: any) {
  const [dataSource, setDataSource] = useState<any[]>([])
  inputs[DATASOURCE_INPUT_ID]?.((val: any[]) => {
    setDataSource(val)
  })
  const template = data.templates?.map?.(mapFun)?.join?.(' ')
  const [columnGap,rowGap] = data.gap
  const style: CSSProperties = {
    columnGap,
    rowGap,
    display: 'grid',
    gridAutoFlow: data.direction == 'ver' ? 'column' : 'row'
  }
  if (data.direction == 'hor') {
    style.gridTemplateColumns = template
  } else {
    style.gridTemplateRows = template
  }
  const items: React.ReactElement[] = []
  if (Array.isArray(dataSource)) {
    dataSource.forEach((item, index) => {
      for (let c = 1; c <= data.templates?.length || 0; c++) {
        const id = `slot_${1}x${c}`
        const key = `${id}_${index}`
        items.push(<div>{slots[id]?.render?.({inputValues: { item, index }, key })}</div>)
      }
    })
  }
  return <div style={style}>{items}</div>
}


export default function (props: any) {
  return props.env.edit ? <EditRender {...props} /> : <RuntimeRender {...props} />
}
